const { urlencoded } = require("body-parser");
const express = require("express");
const router = express.Router(); //生成路由对象，用来定义接口
const data = require("../data/userList");
const url = require('url')

let newData = JSON.parse(JSON.stringify(data))
    //定义一个get请求
router.get("/user", function(req, res) {
    res.send(newData)
})

//定义一个post请求
router.post("/user", function(req, res) {
    let index01 = newData.findIndex(item => item.id == req.body.id)
    let flag;
    flag = newData.some((item, index) => {
        return item.userName === req.body.userName && index !== index01
    })
    if (flag) {
        res.send('修改数据失败')
    } else {
        newData[index01] = req.body
        res.send('修改数据成功')
    }

})

//定义一个delete请求
router.delete("/user", function(req, res) {
    console.log(url.parse(req.url, true).query);
    let id = url.parse(req.url, true).query.id;
    let index = newData.findIndex(item => item.id == id);
    if (index !== -1) {
        newData.splice(index, 1)
        res.send('删除成功')
    } else {
        res.send('没有该用户id')
    }
})

//定义一个put请求
router.put("/user", function(req, res) {
    let obj = req.body;
    let flag;
    flag = newData.some(item => item.userName === obj.userName)
    if (!flag) {
        newData.unshift(obj)
        res.send('添加数据成功')
    } else {
        res.send("添加数据失败")
    }
})
module.exports = router;